package com.fishingwithme.android.ui.screens.my.points

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.fishingwithme.android.R
import com.fishingwithme.android.data.local.PreferencesManager
import com.fishingwithme.android.data.model.CreditLevelRule
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.theme.LVL_ICONS
import com.fishingwithme.android.ui.viewmodels.CreditLevelsUiState
import com.fishingwithme.android.ui.viewmodels.CreditLevelsViewModel
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreditLevelScreen(
    navController: NavController,
    lvl: Int,
    viewModel: CreditLevelsViewModel = hiltViewModel()
) {

    val uiState by viewModel.uiState.collectAsState()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.credit_level_title)) },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(
                            imageVector = Icons.Default.ArrowBack,
                            contentDescription = stringResource(R.string.back)
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(AppDimensions.SPACING_16)
        ) {
            when (uiState) {
                is CreditLevelsUiState.Loading -> {
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }

                is CreditLevelsUiState.Error -> {
                    val errorState = uiState as CreditLevelsUiState.Error
                    Box(
                        modifier = Modifier.fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text(
                                text = errorState.message,
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.error
                            )
                            Spacer(modifier = Modifier.height(AppDimensions.SPACING_16))
                            Button(onClick = { viewModel.retry() }) {
                                Text(text = stringResource(R.string.retry))
                            }
                        }
                    }
                }

                is CreditLevelsUiState.Success -> {
                    val successState = uiState as CreditLevelsUiState.Success
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState())
                    ) {
                        successState.levels.forEachIndexed { index, level ->
                            val currentLevel = lvl
                            val levelId = level.levelId?.toIntOrNull() ?: 0
                            val isCurrent = levelId == currentLevel

                            LevelItem(
                                level = level,
                                isCurrent = isCurrent
                            )

                            if (index < successState.levels.size - 1) {
                                Divider(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = AppDimensions.SPACING_8),
                                    color = MaterialTheme.colorScheme.outlineVariant
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun LevelItem(level: CreditLevelRule, isCurrent: Boolean) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = AppDimensions.SPACING_8)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            val lvlPnt = level.levelId?.toInt()
            // Level icon
            val levelIconResId = lvlPnt?.let { uriInt ->
                LVL_ICONS[uriInt]
            } ?: R.mipmap.lvl_11 // Default icon

            Icon(
                painter = painterResource(id = levelIconResId),
                contentDescription = "Level Icon",
                modifier = Modifier.size(AppDimensions.ICON_SIZE_96),
                tint = Color.Unspecified
            )

            Spacer(modifier = Modifier.width(AppDimensions.SPACING_16))

            // Level indicator
            Box(
                modifier = Modifier
                    .size(40.dp),
                contentAlignment = Alignment.Center
            ) {
                if (isCurrent) {
                    // Current level with border
                    Box(
                        modifier = Modifier
                            .size(36.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = level.levelId ?: "",
                            style = MaterialTheme.typography.bodyLarge,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.primary
                        )
                    }
                } else {
                    // Regular level
                    Text(
                        text = level.levelId ?: "",
                        style = MaterialTheme.typography.bodyLarge,
                        fontWeight = FontWeight.Normal,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                }
            }

            Spacer(modifier = Modifier.width(AppDimensions.SPACING_16))

            // Level name
            Text(
                text = level.levelName ?: "",
                style = MaterialTheme.typography.bodyMedium,
                fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.Normal,
                color = if (isCurrent) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
            )

            Spacer(modifier = Modifier.weight(1f))

            // Status indicator
            if (isCurrent) {
                Text(
                    text = stringResource(R.string.credit_current_level_indicator),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }

        // Additional level details
        Spacer(modifier = Modifier.height(AppDimensions.SPACING_8))

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            // Core trait
            level.coreTrait?.let {
                Text(
                    text = it,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurface
                )
            }

            // Points range
            val minPoints = level.minPoints ?: 0
            val maxPoints = level.maxPoints ?: 0
            Text(
                text = "$minPoints - $maxPoints",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurface
            )
        }

        // Upgrade threshold
        level.upgradeThreshold?.let {
            Spacer(modifier = Modifier.height(AppDimensions.SPACING_4))
            Text(
                text = it,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurface
            )
        }
    }
}

// Hilt入口点接口，用于在Composable中获取PreferencesManager
@EntryPoint
@InstallIn(SingletonComponent::class)
interface CreditLevelScreenHiltEntryPoint {
    fun preferencesManager(): PreferencesManager
}